package pv.finder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.crypto.spec.OAEPParameterSpec;

import pv.control.SubCategoryView;
import pv.control.SubCategoryAdapter;
import pv.control.SubCategoryView.onSubCategoryListener;
import pv.dto.AbstractDTO;
import pv.dto.DistrictDTO;
import pv.dto.PlaceDTO;
import pv.dto.SubCategoryDTO;
import pv.finder.Values.TYPEPLACE;
import pv.finder.search.DistrictSearch;
import pv.map.CustomInfoWindows;
import pv.map.MapHelper;
import pv.util.Utility;
import android.app.AlertDialog;
import android.app.Application.ActivityLifecycleCallbacks;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;

public class FMMap extends Fragment implements OnCheckedChangeListener,
		DataHelper.LoadDataListener, onSubCategoryListener,
		View.OnClickListener, OnInfoWindowClickListener {
	protected MapHelper mapHelper;
	protected DataHelper dataHelper;
	protected List<PlaceDTO> listPlaces;
	protected Map<Integer, Marker> mapMarker;

	protected int subSelectedID = -1;

	// data
	protected SubCategoryView layoutSubCategory;
	protected SubCategoryAdapter adapSubCategory;
	TYPEPLACE type;

	public FMMap() {

		mapMarker = new HashMap();

	}

	public FMMap(DataHelper dataHelper) {

		this.dataHelper = dataHelper;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mapHelper != null) {
			mapHelper.onResume();
			mapHelper.moveToCurrent();

		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mapHelper != null)
			mapHelper.onPause();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		if (mapHelper != null)
			mapHelper.onSaveInstanceState(outState);
		outState.putInt("subSelectedID", subSelectedID);
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		if (mapHelper != null)
			mapHelper.onLowMemory();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mapHelper != null)
			mapHelper.onDestroy();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mapHelper = new MapHelper(getActivity());
		mapHelper.onCreate(savedInstanceState);
		dataHelper = new DataHelper(getActivity());

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fm_main, null);
		mapHelper.setMapView((MapView) view.findViewById(R.id.map));
		mapHelper.onCreate(savedInstanceState);
		// child on view
		((RadioGroup) view.findViewById(R.id.rgATMGAS))
				.setOnCheckedChangeListener(this);

		((ImageButton) view.findViewById(R.id.btnGPS)).setOnClickListener(this);

		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mapHelper.onActivityCreated(getActivity());

		if (savedInstanceState != null)
			subSelectedID = savedInstanceState.getInt("subSelectedID");

		init();
		((RadioButton) getView().findViewById(
				type == TYPEPLACE.ATM ? R.id.rb_atm : R.id.rb_gas))
				.setChecked(true);

	}

	protected void init() {
		// TODO Auto-generated method stub

		/* for subcategory */
		initSubList();

		/* for data */
		if (dataHelper != null) {

			DistrictSearch search = new DistrictSearch();
			if (listPlaces == null || listPlaces.isEmpty()) {
				DistrictDTO district = new DistrictDTO(6, "1");
				search.setDistrict(district);
				dataHelper.setListener(this);
				dataHelper.loadData(search);
			} else {
				listPlaces = Arrays.asList(dataHelper.getPlaces());
				addMarkerToMap();
			}

			if (type == TYPEPLACE.ATM) {
				// show subcategory
				showSubList();
			}
		} else {
			dataHelper = new DataHelper(getActivity());

		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		switch (checkedId) {
		case R.id.rb_atm:
			showType(Values.TYPEPLACE.ATM);
			break;

		default:
			showType(Values.TYPEPLACE.GAS);
			break;
		}

	}

	@Override
	public void callback(PlaceDTO[] places) {
		// TODO Auto-generated method stub
		if (places != null && places.length > 0) {
			listPlaces = Arrays.asList(places);
			addMarkerToMap();
		}
	}

	protected void addMarkerToMap() {
		addMarkerToMap(listPlaces.toArray(new PlaceDTO[listPlaces.size()]));
	}

	protected void addMarkerToMap(PlaceDTO[] places) {

		try {
			mapHelper.clear();
			mapMarker.clear();
			Marker m;
			boolean isGAS = ((RadioButton) getView().findViewById(R.id.rb_gas))
					.isChecked();
			for (int i = 0; i < places.length; i++) {
				m = mapHelper.addMarker(
						new LatLng(Double.valueOf(places[i].getLatitude()),
								Double.valueOf(places[i].getLongitude())),
						places[i].getName(), "", getMarkerBitmap(places[i]));

				m.setVisible(isGAS
						&& places[i].getCategory_id() == Values
								.getIDType(TYPEPLACE.GAS));
				if (m != null)
					mapMarker.put(i, m);
			}
			mapHelper.getMap().setInfoWindowAdapter(
					new CustomInfoWindows(getActivity()));
			mapHelper.getMap().setOnInfoWindowClickListener(this);
		} catch (Exception e) {
			// TODO: handle exception
			Utility.LogE(this.getClass(), e);

		}

	}

	protected void showType(Values.TYPEPLACE type) {
        if(mapHelper!=null){
            mapHelper.clearRoute();
        }
		try {
			if (type == TYPEPLACE.GAS) {
				showGas();
			} else {
				showATM();

			}
		} catch (Exception e) {
			// TODO: handle exception
			Utility.LogE(this.getClass(), e);

		}
	}

	public void showATM() {

		showATM(subSelectedID);

	}

	public void showATM(int subID) {
		showSubList();
		PlaceDTO dto;
		for (int i = 0; i < listPlaces.size(); i++) {
			dto = listPlaces.get(i);
			mapMarker.get(i).setVisible(
					dto.getCategory_id() == Values.getIDType(TYPEPLACE.ATM)
							&& dto.getSub_category_id() == subID);
		}
	}

	public void showGas() {
		PlaceDTO dto;
		hideSubList();
		for (int i = 0; i < listPlaces.size(); i++) {
			dto = (PlaceDTO) listPlaces.get(i);
			mapMarker.get(i).setVisible(
					Values.getIDType(TYPEPLACE.GAS) == dto.getCategory_id());
		}

	}

	protected Bitmap getMarkerBitmap(PlaceDTO dto) {
		return dto.getCategory_id() == 1 ? BitmapFactory.decodeResource(
				getResources(), R.drawable.gas) : BitmapFactory.decodeResource(
				getResources(), FMMap.getDrawableATM(dto.getSub_category_id()));
	}

	protected static final int getDrawableATM(int subCategoryID) {

		// final Random random = new Random();
		// int index = random.nextInt(5);
		int index = subCategoryID % 5;
		switch (index) {
		case 0:
			return R.drawable.atm_1;

		case 1:
			return R.drawable.atm_2;
		case 2:

			return R.drawable.atm_3;
		case 3:

			return R.drawable.atm_4;
		case 4:

			return R.drawable.atm_5;

		default:
			return R.drawable.atm_6;
		}

	}

	protected void initSubList() {
		adapSubCategory = new SubCategoryAdapter(getActivity());
		layoutSubCategory = new SubCategoryView(getActivity(),
				(HorizontalScrollView) getView().findViewById(
						R.id.svSubcategory));
		layoutSubCategory.setAdapter(adapSubCategory);

		List<SubCategoryDTO> listSub = Arrays.asList(dataHelper
				.getSubcategorys());
		if (adapSubCategory == null || adapSubCategory.getCount() == 0) {

			if (listSub != null) {
				adapSubCategory.setListData(listSub);
			}

		}
		layoutSubCategory.notifyDataSetChanged();
		subSelectedID = adapSubCategory.getSelectedItem().getId();
		layoutSubCategory.setOnSubCategorySelected(this);

	}

	protected void showSubList() {
		getView().findViewById(R.id.svSubcategory).setVisibility(View.VISIBLE);
	}

	protected void hideSubList() {
		getView().findViewById(R.id.svSubcategory).setVisibility(View.GONE);
	}

	public void onBackPress() {
		// new AlertDialog.Builder(getActivity())
		// .setMessage(getString(R.string.app_name))
		// .setPositiveButton(getString(android.R.string.yes),
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// getActivity().finish();
		// }
		// })
		// .setNegativeButton(getString(android.R.string.no),
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		//
		// }
		// }).show();
		getActivity().finish();
	}

	@Override
	public void onSubCategorySelected(int position) {
		// TODO Auto-generated method stub
		subSelectedID = adapSubCategory.getItem(position).getId();
		showATM();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btnGPS) {
			if (mapHelper != null) {
				mapHelper.moveToCurrent();
			}
		}

	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		// TODO Auto-generated method stub
		if (mapHelper != null && marker != null) {
			mapHelper.route(String.valueOf(marker.getPosition().latitude) + ","
					+ String.valueOf(marker.getPosition().longitude),
					MapHelper.MODE_DRIVING);
		}

	}
}
